<template>
  <div class="common-layout">
    <el-container>
      <!-- 搜索区 -->
      <el-header>
        <el-form :inline="true" style="width: 2000px">
          <el-form-item label="审批状态:" style="width: 200px">
            <el-select v-model="form.status" placeholder="请选择">
              <el-option label="请选择" :value="-1"></el-option>
              <el-option label="提交" :value="0"></el-option>

              <el-option label="处理中" :value="1"></el-option>
              <el-option label="已完成" :value="2"></el-option>
              <el-option label="驳回" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请人:" style="width: 200px">
            <el-input v-model="form.userName" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="请假时间:" style="width: 400px">
            <el-date-picker
              style="width: 150px"
              v-model="form.startTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              clearable
            />
            至
            <el-date-picker
              style="width: 150px"
              v-model="form.endTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="getLeaveRequests()"
              style="margin-left: -30px"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
      </el-header>
      <el-main>
        <div style="margin: 40px">
          <el-button type="primary" @click="CreateLeaveRequests()"
            >请假申请</el-button
          >
        </div>
        <!-- 显示 -->
        <div>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column fixed type="index" label="序号" width="55" />
            <el-table-column prop="userName" label="姓名" width="100" />
            <el-table-column prop="depId" label="部门" width="100">
              <template #default="scoped">
                {{
                  scoped.row.depId == 1
                    ? "IT信息部"
                    : scoped.row.depId == 2
                    ? "人力资源部"
                    : scoped.row.depId == 3
                    ? "财务部"
                    : scoped.row.depId == 4
                    ? "销售部"
                    : "行政部"
                }}
              </template>
            </el-table-column>
            <el-table-column prop="leaveType" label="请假类别" width="100">
              <template #default="scoped">
                {{
                  scoped.row.leaveType == 1
                    ? "事假"
                    : scoped.row.leaveType == 2
                    ? "病假"
                    : scoped.row.leaveType == 3
                    ? "婚假"
                    : scoped.row.leaveType == 4
                    ? "丧假"
                    : scoped.row.leaveType == 5
                    ? "产假"
                    : scoped.row.leaveType == 6
                    ? "补休"
                    : scoped.row.leaveType == 7
                    ? "工伤"
                    : "其他"
                }}
              </template>
            </el-table-column>
            <el-table-column prop="leavetime" label="请假时间" width="200" />
            <el-table-column prop="totalhours" label="总工时(H)" width="100" />
            <el-table-column prop="endTime" label="报道时间" width="120">
              <template #default="scoped">
                {{ scoped.row.endTime.substring(0, 10) }}
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="请假事由" width="100" />
            <el-table-column prop="depheadsName" label="部门领导" width="100" />

            <el-table-column prop="status" label="申请状态" width="120">
              <template #default="scoped">
                {{
                  scoped.row.status == 0
                    ? "提交"
                    : scoped.row.status == 1
                    ? "处理中"
                    : scoped.row.status == 3
                    ? "驳回"
                    : "已完成"
                }}
              </template>
            </el-table-column>
            <!-- <el-table-column
              prop="reasonrejection"
              label="驳回原因"
              width="100"
            >
              <template #default="scoped">
                {{ scoped.row.status == 3 ? "不通过" : "" }}
              </template>
            </el-table-column> -->

            <el-table-column label="驳回原因" width="200">
              <template #default="{ row }">
                <div v-if="row.status === 3" class="rejection-reason">
                  <el-tooltip :content="row.reasonrejection" placement="top">
                    <span>{{ row.reasonrejection }}</span>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="120">
              <template #default="scoped">
                {{ scoped.row.createTime.substring(0, 10) }}
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="190">
              <template #default="scoped">
                <el-button
                  :disabled="
                    scoped.row.status == 2 ||
                    scoped.row.status == 1 ||
                    scoped.row.status == 3
                  "
                  type="primary"
                  size="small"
                  @click="updataLeaveRequests(scoped.row.applicationId)"
                  >修改</el-button
                >
                <el-button
                  :disabled="
                    scoped.row.status == 2 ||
                    scoped.row.status == 1 ||
                    scoped.row.status == 3
                  "
                  type="danger"
                  size="small"
                  @click="delLeaveRequests(scoped.row.applicationId)"
                  >删除</el-button
                >
                <el-button
                  type="warning"
                  size="small"
                  :disabled="
                    store.ccstore.roleName == '员工' ||
                    scoped.row.status == 2 ||
                    scoped.row.status == 3
                  "
                  @click="AppUpdataView(scoped.row.applicationId)"
                  >审批</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div>
            <el-pagination
              v-model:current-page="page.PageIndex"
              v-model:page-size="page.PageSize"
              :page-sizes="[5, 10, 15, 20]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="page.totalCount"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>

        <!-- 修改 -->
        <div>
          <el-dialog v-model="dialogFormVisible" title="修改界面" width="500">
            <el-form :model="form">
              <el-form-item label="申请人" :label-width="formLabelWidth">
                <el-input v-model="form.userName" autocomplete="off" />
              </el-form-item>
              <el-form-item label="部门" :label-width="formLabelWidth">
                <el-select v-model="form.depId" placeholder="请选择部门">
                  <el-option label="请选择部门" :value="0"></el-option>
                  <el-option label="IT信息部" :value="1"></el-option>
                  <el-option label="人力资源部" :value="2"></el-option>
                  <el-option label="财务部" :value="3"></el-option>
                  <el-option label="销售部" :value="4"></el-option>
                  <el-option label="行政部" :value="5"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="请假类别" :label-width="formLabelWidth">
                <el-radio-group v-model="form.leaveType">
                  <el-radio label="事假" :value="1">事假</el-radio>
                  <el-radio label="病假" :value="2">病假</el-radio>
                  <el-radio label="婚假" :value="3">婚假</el-radio>
                  <el-radio label="丧假" :value="4">丧假</el-radio>
                  <el-radio label="产假" :value="5">产假</el-radio>
                  <el-radio label="补休" :value="6">补休</el-radio>
                  <el-radio label="工伤" :value="7">工伤</el-radio>
                  <el-radio label="其他" :value="8">其他</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item label="请假时间：">
                <div class="time-range">
                  <el-date-picker
                    @change="handleTimeChange"
                    v-model="form.startTime"
                    type="datetime"
                    placeholder="开始时间"
                    value-format="YYYY-MM-DDTHH:mm:ss"
                  />
                  <span class="time-separator">至</span>
                  <el-date-picker
                    @change="handleTimeChange"
                    v-model="form.endTime"
                    type="datetime"
                    placeholder="结束时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </div>
              </el-form-item>
              <el-form-item label="总工时" :label-width="formLabelWidth">
                <el-input v-model="form.totalhours" autocomplete="off" />
              </el-form-item>
              <el-form-item label="请假事由：" :label-width="formLabelWidth">
                <el-input v-model="form.reason" type="textarea"></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="upLeaveRequests()">修改</el-button>
                <el-button type="primary" @click="dialogFormVisible = false">
                  取消
                </el-button>
              </div>
            </template>
          </el-dialog>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from "element-plus";
import moment from "moment";
import { compile, computed, nextTick, onMounted, reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useCounterStore } from "@/stores/counter";
import DepData from "@/stores/departmentData";
import axios from "axios";
import { ElTree } from "element-plus";
import type { AnyColumn } from "element-plus/es/components/table-v2/src/common.mjs";
import { pa } from "element-plus/es/locales.mjs";
//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();
const route = useRoute();
//跳转到请假申请页面
const CreateLeaveRequests = () => {
  router.push({
    path: "/CreateLeaveRequestsView",
  });
};

// 显示
const tableData = ref([]);
onMounted(() => {
  getLeaveRequests();
});

const page = ref({
  PageIndex: 1,
  PageSize: 15,

  totalCount: 0,
  totalPage: 0,
  DepId: 0,
  Heads: 0,
});

// 显示请假申请
const getLeaveRequests = () => {
  axios
    .get(
      "https://localhost:7174/api/Message/GetLeaveApplication/GetLeaveApplication",
      {
        params: {
          PageIndex: page.value.PageIndex,
          PageSize: page.value.PageSize,
          startTime: form.startTime,
          endTime: form.endTime,
          userName: store.ccstore.userName,
          status: form.status,
          DepId: page.value.DepId,
          Heads: page.value.Heads,
        },
      }
    )
    .then((res) => {
      console.log(res.data.data);
      tableData.value = res.data.data;
      page.value.totalCount = res.data.totalCount;
      page.value.totalPage = res.data.totalPage;
    });
};

// 删除(逻辑删除)
const delLeaveRequests = (applicationId: number) => {
  alert(applicationId);
  axios
    .put("https://localhost:7272/api/Message/DelLeaveApplication", {
      applicationId: applicationId,
    })
    .then((res) => {
      if (res.data.code == 204) {
        ElMessage.success(res.data.msg);
        return;
      } else {
        ElMessage.success(res.data.msg);
        return;
      }
    });
};

//#region  修改
const dialogTableVisible = ref(false);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const form = reactive({
  applicationId: 0,
  userName: "",
  depId: 0,
  leaveType: 0,
  startTime: "",
  endTime: "",
  leavetime: "",
  totalhours: 0,
  reason: "",
  depheadsName: "",
  status: -1,
  createTime: "",
  isDelete: false,
});

const formatISODate = (date: any) => {
  if (!date) return null;
  return moment(date).toISOString(true); // 保留时区信息
};

// 修改--反填
const updataLeaveRequests = (applicationId: number) => {
  // alert(applicationId);
  dialogFormVisible.value = true;
  axios
    .get("https://localhost:7174/api/Message/FanTianLeaveApplication", {
      params: { ApplicationId: applicationId },
    })
    .then((res) => {
      console.log(res.data.data[0]);
      form.applicationId = res.data.data[0].applicationId;
      form.userName = store.ccstore.userName;
      form.depId = res.data.data[0].depId;
      form.leaveType = res.data.data[0].leaveType;
      form.startTime = res.data.data[0].startTime;
      form.endTime = res.data.data[0].endTime;
      form.depheadsName = res.data.data[0].depheadsName;
      form.status = res.data.data[0].status;
      form.createTime = res.data.data[0].createTime;
      form.reason = res.data.data[0].reason;
      form.totalhours = res.data.data[0].totalhours;
      form.leavetime = res.data.data[0].leavetime;
    });
};

// 统一增加日期格式化处理
const formatDateTime = (dateString: string) => {
  if (!dateString) return null;
  return moment(dateString).isValid()
    ? moment(dateString).format("YYYY-MM-DD HH:mm:ss")
    : null;
};

//修改
const upLeaveRequests = () => {
  // 转换日期格式
  const submitData = {
    ...form,
    startTime: formatISODate(form.startTime),
    endTime: formatISODate(form.endTime),
  };

  // 验证日期格式
  if (
    !moment(submitData.startTime, moment.ISO_8601).isValid() ||
    !moment(submitData.endTime, moment.ISO_8601).isValid()
  ) {
    throw new Error("包含无效的时间格式");
  }

  // 增加空值校验
  if (!submitData.startTime || !submitData.endTime) {
    ElMessage.error("请选择有效的时间范围");
    return;
  }

  // 增加时间顺序校验
  if (moment(submitData.endTime).isBefore(moment(submitData.startTime))) {
    ElMessage.error("结束时间不能早于开始时间");
    return;
  }

  axios
    .put("https://localhost:7272/api/Message/UpLeaveApplication", form)
    .then((res) => {
      console.log(res.data);
      if (res.data.code == 206) {
        ElMessage.success(res.data.msg);
        form.status = -1;
        form.userName = "";
        form.startTime = "";
        form.endTime = "";
        getLeaveRequests();
        dialogFormVisible.value = false;

        return;
      } else {
        ElMessage.success(res.data.msg);
        return;
      }
    });
};

const handleTimeChange = () => {
  nextTick(() => {
    // 确保DOM更新后计算
    calculateTotalHours();
    updateLeaveTime();

    // 自动补全秒数
    if (form.startTime && form.startTime.length === 16) {
      form.startTime += ":00";
    }
    if (form.endTime && form.endTime.length === 16) {
      form.endTime += ":00";
    }
  });
};

// 提取计算方法
const calculateTotalHours = () => {
  if (!form.startTime || !form.endTime) {
    form.totalhours = 0;
    return;
  }

  const start = new Date(form.startTime);
  const end = new Date(form.endTime);

  // 处理跨天计算
  const startDay = start.getDate();
  const endDay = end.getDate();
  const daysDiff = endDay - startDay;

  let totalHours = 0;

  // 当天请假
  if (daysDiff === 0) {
    totalHours = (end - start) / (1000 * 60 * 60);
  }
  // 跨天请假
  else {
    // 第一天工时（17点 - 开始小时）
    const firstDayHours = 17 - start.getHours();
    // 中间整天数（每天8小时）
    const middleDaysHours = (daysDiff - 1) * 8;
    // 最后一天工时（结束小时 - 9）
    const lastDayHours = end.getHours() - 9;

    totalHours = firstDayHours + middleDaysHours + lastDayHours;
  }

  form.totalhours = Math.round(totalHours * 100) / 100; // 保留两位小数
};

// 更新请假时间显示
const updateLeaveTime = () => {
  if (form.startTime && form.endTime) {
    const format = "YYYY-MM-DD HH:mm";
    form.leavetime = `${moment(form.startTime).format(format)} 至 ${moment(
      form.endTime
    ).format(format)}`;
  } else {
    form.leavetime = "";
  }
};

// 日期选择器的可选时间范围
const pickerOptionss = {
  disabledDate(time: any) {
    return false; // 不限制日期选择
  },
  selectableRange: "09:00:00 - 17:00:00", // 限制可选时间范围为 09:00 到 17:00
};
//计算请假时长
const duration = computed(() => {
  // 空值保护
  if (!form.startTime || !form.endTime) return { totalHours: 0 };

  // 时间对象转换（考虑Safari兼容性）
  const start = new Date(form.startTime);
  const end = new Date(form.endTime);

  // 时间差校验
  if (end < start) return { days: 0, hours: 0 };

  // 计算毫秒差
  const diffMs = end.getTime() - start.getTime();

  // 转换为小时（向上取整处理最小请假单位）
  // const totalHours = Math.ceil(diffMs / (1000 * 60 * 60));
  const startDay = start.getDate();
  const endDay = end.getDate();
  const daysDiff = endDay - startDay; //时差
  // alert(daysDiff)
  const startHour = start.getHours();
  // console.log(startHour,"开始")
  const endHour = end.getHours();
  let totalHours = 0;
  if (daysDiff === 0) {
    totalHours = endHour - startHour;
  } else {
    // 第一天剩余工时
    const firstDayHours = 17 - startHour;
    // 中间完整天数工时
    const middleDaysHours = (daysDiff - 1) * 8;
    // 最后一天工时
    const lastDayHours = endHour - 9;
    totalHours = firstDayHours + middleDaysHours + lastDayHours;
    // alert(totalHours)
  }

  form.totalhours = totalHours;
  console.log(totalHours, "总工时");
  const days = Math.floor(totalHours / 8);
  const remainingHours = totalHours % 8; // 按8小时/天计算
  // 按8小时/天计算
  return {
    /* days: days,
    hours: remainingHours, */
    totalHours: form.totalhours,
  };
});

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  page.value.PageSize = val;
  getLeaveRequests();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  page.value.PageIndex = val;
  getLeaveRequests();
};
//#endregion

//#region  审批

const AppUpdataView = (applicationId: number) => {
  // alert(applicationId);
  router.push({
    path: "/AppUpdataView",
    query: { applicationId: applicationId },
  });
};

//#endregion
</script>

<style scoped>
</style>